<!DOCTYPE html>
<html>
<head>
    <title>安全巡查详情</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width,height=device-height,inital-scale=1.0,maximum-scale=1.0,user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<meta name="format-detection" content="telephone=no" />
<meta charset="utf-8" />
 <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
    <link rel="stylesheet" href="../css/weui.css"/>
    <link rel="stylesheet" href="../css/example.css"/>
<style type="text/css">
    body, html,#allmap {width: 100%;height: 70%;margin:0;font-family:"微软雅黑";}
</style>
<script type="text/javascript" src="https://api.map.baidu.com/api?v=2.0&ak=cR98TwX2FnKTpANIOYhMYMot9a4ioxjc"></script>
<script type="text/javascript" src="https://api.map.baidu.com/library/CurveLine/1.5/src/CurveLine.min.js"></script>
<script src="https://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
</head>
<body>
<form action="" novalidate>
	<div class="weui-cells weui-cells_form">
            <div class="weui-cell weui-cell_access">
                <div class="weui-cell__hd"><label class="weui-label">资产名称</label></div>
                <div id="address" class="weui-cell__bd">
                </div>
                <div class="weui-cell__ft"></div>
            </div>
    </div>
    
    <div class="weui-cells weui-cells_form">
            <div class="weui-cell">
                <div class="weui-cell__hd"><label class="weui-label">管理分区</label></div>
                <div id="manageRegion" class="weui-cell__bd">
                </div>
            </div>
    </div>
     
    <div class="weui-cells weui-cells_form">
     <div class="weui-cell">
        <div class="weui-cell__hd"><label class="weui-label">检查结果</label></div>
        <div  class="weui-cell__bd">
          <input id="check_name" class="weui-input" />
        </div>
     </div>
    </div>
   	
	<div class="weui-cells weui-cells_form">
        <div class="weui-cell">
                <div class="weui-cell__hd"><label class="weui-label">检查时间</label></div>
                <div  class="weui-cell__bd">
                  <input id="happenTime" class="weui-input" type="date" />
                </div>
        </div>
    </div>
    
    <div class="weui-cells weui-cells_form">
        <div class="weui-cell">
                <div class="weui-cell__hd"><label class="weui-label">录入时间</label></div>
                <div id="insertTime" class="weui-cell__bd">
                </div>
        </div>
    </div>
    
     <div class="weui-cells weui-cells_form">
            <div class="weui-cell">
                <div class="weui-cell__hd"><label class="weui-label">录入人员</label></div>
                <div id="username" class="weui-cell__bd">
                </div>
            </div>
    </div>
    
    <div class="weui-cells weui-cells_form">
     <div class="weui-cell">
        <div class="weui-cell__hd"><label class="weui-label">备注</label></div>
        <div  class="weui-cell__bd">
         <input id="remark" class="weui-input" />
        </div>
     </div>
    </div>
    
    <div class="weui-cells__title">检查内容</div>
    <div class="weui-cells weui-cells_form">
            <div class="weui-cell">
                <div class="weui-cell__bd">
                  <textarea id="check_circs" class="weui-textarea" rows="3"></textarea>
                </div>
            </div>
        </div>
       
 </form>

 <div class="weui-cells__title">检查位置</div>
 <div id="allmap"></div>   
    
    <div class="weui-panel weui-panel_access">
     <div class="weui-panel__hd">安全检查图片</div>  
       <div id="img" class="weui-panel__bd">
       </div>  
       <div class="weui-uploader__input-box" id="showPicker">
       	</div>  
   </div>  

   <a href="javascript:;" id="save" class="weui-btn weui-btn_plain-primary">保存</a>

</body>

<script type="text/javascript">
  function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
   }

  var check_id=getQueryString("check_id");

  var longitude=getQueryString("longitude");
  var latitude=getQueryString("latitude");
  
    // 百度地图API功能
    var map = new BMap.Map("allmap");    // 创建Map实例

	var point = new BMap.Point(longitude, latitude);
    
    var pointStart=point;

	var str = "我的位置";
	var opts = {
			   position : point,    // 指定文本标注所在的地理位置
			   offset   : new BMap.Size(-getByteLen(str)*3, 5)    //设置文本偏移量
			}	
	var label = new BMap.Label(str, opts);  // 创建文本标注对象
	label.setStyle({
					 fontSize : "12px",
					 height : "20px",
					 lineHeight : "20px",
					 fontFamily:"微软雅黑"
				  });
    map.addOverlay(label);
    map.enableScrollWheelZoom(true);
    
    var geoc = new BMap.Geocoder();
  	
	function keyDown(e) {   		  
	　   var keycode = e.which;   //取得对应的键值（数字）  	  
	　   var realkey = String.fromCharCode(e.which); //取得代表改键的真正字符  
	   var val = document.getElementById("input").value;
	　   if(keycode==13){
		   local.search(val);
	　   }
	 }     
    
	$.ajax({
        type: "POST",
        url: "/shambles/mobile/hidden/selectCheckByCheckId.do",
        data: { "check_id":check_id},
        dataType: "json",
        error: function (request){
     	   console.log(request);
        },
        success: function (text) {   
        	console.log(text);
     	   var obj=text.hidden_Check;
     	   var imgs=text.fileBytes;
  
             	   var check_id=obj.check_id;
  
             	   var distance=null;
             	   console.log(obj.name+"   "+obj.detail+"  "+obj.lng+"   "+obj.lat);
             	   if(obj.lng!=""&&obj.lat!=""){
             	   	  distance=getDistance(obj.lng,obj.lat);
             	   	var point = new BMap.Point(obj.lng,obj.lat);
             	   	var pointEnd=point;
             	    map.centerAndZoom(point, 12);
             	    var marker = new BMap.Marker(point); // 创建点
             		map.addOverlay(marker);    //增加点
             	   }
             	 
             	  navigation(pointStart, pointEnd);
             	   
             	  var terminal=obj.terminal;
             	  if(terminal!=null&&terminal!=""){
             		  if(terminal=="PC"){
             			 var username=document.createElement("span");
             			 username.innerHTML=obj.user_name;
                         $("#username").append(username);
             		  }else if(terminal=="Wechat"){
             			  $.get("/shambles/mobile/hidden/selectNameBycampusAdmin.do",{
             				 	campusAdmin:obj.campusAdmin
             			  		},function(text){
             			  			var name = $.parseJSON(text);
             			  			var username=document.createElement("span");
                        			 username.innerHTML=name.name;
                                    $("#username").append(username);
             			  		});	
             		  }
             	  }
             	   
             	  var address=document.createElement("span");
               	  address.innerHTML=obj.address;
                  $("#address").append(address);
                  
                  $("#address").on("click",function(){
                	  clickEvent(obj.guid);
                  });
                  
                  var manageRegion=document.createElement("span");
                  manageRegion.innerHTML=obj.manageRegion;
                  $("#manageRegion").append(manageRegion);
             	   
             	  //var check_name=document.createElement("span");
             	 //check_name.innerHTML=obj.check_name;
                  //$("#check_name").append(check_name);
                  
                  $("#check_name").val(obj.check_name);
                  $("#name").val(obj.name);
                  $("#principal").val(obj.principal);
                  
                 // var time=actionTime(obj.date);
                 // var date=document.createElement("span");
                 // date.innerHTML=time;
                 // $("#date").append(date);
                  
                 var time=actionTime(obj.happen_time);
                  console.log(time);
                  $("#happenTime").val(time);
                 
                  var time=actionTime(obj.date);
                  var insertTime=document.createElement("span");
                  insertTime.innerHTML=time;
                  $("#insertTime").append(insertTime);
                 
                 // var remark=document.createElement("span");
                 // remark.innerHTML=obj.remark;
                 // $("#remark").append(remark);
                  
                  
                 
                  $("#remark").val(obj.remark);
                 
                  
                 // var check_circs=document.createElement("textarea");
                 // check_circs.setAttribute("class","weui-textarea");
                 // check_circs.innerHTML=obj.check_circs;
                 // $("#check_circs").append(check_circs);
                  
                 $("#check_circs").val(obj.check_circs);
                 
                  console.log(imgs);
                  if(imgs!=null){
                  	   var i = 0;
                         for(; i < imgs.length; i++){
                      	   
                      	  var data=imgs[i];
                      	  var name=data.name;
                      	  var uri=data.compressUri;
                      	  var date=data.date;
                      	  var panel=document.createElement("div");
                      	  panel.setAttribute("class","weui-panel__bd");
                        	   var a=document.createElement("a");
                       	   a.setAttribute("class","weui_grid");
                       	   var a=document.createElement("a");
                       	  a.setAttribute("href","javascript:void(0);");
                       	   a.setAttribute("class","weui-media-box weui-media-box_appmsg");
                       	   var div=document.createElement("div");
                       	  	div.setAttribute("class","weui-media-box__hd");
                       	  
                  	   	 	 src="/shambles/"+uri;
                  	  	  	var img=document.createElement("img");
                  	  	  	img.setAttribute("class","weui-media-box__thumb");
                            	img.setAttribute("src",src);
                          
                         	  	div.appendChild(img);
                         	   		
                         	  	div2=document.createElement("div");
                         	  		div2.setAttribute("class","weui-media-box__bd");
                         	 		h4=document.createElement("h4");
                         	 		h4.setAttribute("class","weui-media-box__title");
                         	 	 	h4.innerHTML=name;
                         	  	 	p=document.createElement("p");
                         	  	 	p.setAttribute("class","weui-media-box__desc");
                         	  	 	p.innerHTML=date;
                         	     div2.appendChild(h4);
                         	     div2.appendChild(p);
                         	   a.appendChild(div);
                         	   a.appendChild(div2);
                         	   panel.appendChild(a);
                  	      	  $("#img").append(panel);
                         }
          		   
          	   		}
        }
    });
    
    
	function clickEvent(guid){
	  guid=encodeURI(guid);	
  	  wx.getLocation({
	         success : function(res) {
	            // alert(JSON.stringify(res));
	            var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
	            // $("#latitude").val(latitude);
	            var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
	            
	            $.get("/shambles/mobile/map/baiduSwitch.do",{ //微信地理位置坐标转换成百度地图坐标
	              	 longitude:longitude,
	              	 latitude:latitude               	 
	               },function(text){
	              	 var obj = $.parseJSON(text);
	              	 var result=obj.result;
	              	 var lat=result[0].y;
	              	 var lng=result[0].x;
	              	location.href="../../assetAdmin/assetDetail.html?guid="+guid+"&latitude="+lat+"&longitude="+lng;
	            });
	            
	        },
	        cancel : function(res) {
	     	   console.log('用户拒绝授权获取地理位置');
	        }
	    });         	  
    }
	
	function actionTime(value){
  	    var date = new Date(value); 
  	    Y = date.getFullYear() + '-';
  	    M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
  	  	D = date.getDate()<10?'0'+date.getDate():date.getDate();
  	    h = date.getHours() + ':';
  	    m = date.getMinutes() + ':';
  	    s = date.getSeconds(); 
  		return Y+M+D;
  	}

    
    
    function getByteLen(val) {    //传入一个字符串
        var len = 0;
        for (var i = 0; i < val.length; i++) {
            if (val[i].match(/[^\x00-\xff]/ig) != null) //全角 
                len += 2; //如果是全角，占用两个字节  如果mysql中某字段是text, 如果设置编码为utf-8,那么一个中文是占3个字节, gbk是两个字节
            else
                len += 1; //半角占用一个字节
        }
        return len;
     }  
    
    function getDistance(lng,lat){
    	var pointA = new BMap.Point(longitude,latitude);  // 创建点坐标A--大渡口区
    	var pointB = new BMap.Point(lng,lat);  // 创建点坐标B--江北区
    	var d=map.getDistance(pointA,pointB)/1000;
    	return d.toFixed(2)+' KM';  //获取两点距离,保留小数点后两位
    }
    
    //线路
    function navigation(p1, p2) {
            var points = [p1,p2];
        	var curve = new BMapLib.CurveLine(points, {strokeColor:"blue", strokeWeight:3, strokeOpacity:0.5});
        	map.addOverlay(curve);
    }
    
    $("#save").on("click",function(){

    	geoc.getLocation(point, function(rs){
    	    var addComp;
    	  	addComp = rs.addressComponents;
        	
        	var check_name=$("#check_name").val();
        	var happenTime=$("#happenTime").val();
        	var remark=$("#remark").val();
        	var check_circs=$("#check_circs").val();
        	var addComp1=JSON.stringify(addComp);

        	 $.post("/shambles/mobile/hidden/updateHiddenCheck.do",
        		  {
        		 	check_id:check_id,
        		 	check_name:check_name,
    		    	happenTime:happenTime,
    		    	remark:remark,
    		    	check_circs:check_circs,
    		    	addComp:addComp1,
    		    	lng:longitude,
    		    	lat:latitude
    		    }, function(data){
    	        	var obj = $.parseJSON(data);
    		    	if (obj.status == 0) {
    		        	alert("更新"+name+"安全巡查记录失败!");
    		        	console.log(obj.status);
    		        } else if (obj.status == 1) {
    		            //存储到服务器成功后的处理
    		            //
    		            var check_id=obj.check_id;
    		        	alert("更新"+name+"安全巡查记录成功!");
    		        	
    		        	location.href="CheckInfoDetail.html?check_id="+check_id+"&latitude="+latitude+"&longitude="+longitude;
    		        	
    		        	/*
    		        	var images = {
    		        	   		 localId: [],
    		        	    	serverId: []
    		        	  	   };
          	        	    		 
    	    			 var imagename=prompt("请输入安全巡查图片的名称 : ","");
    	    		 
    	    			 if(imagename==null){
    	    				 imagename="无标题";
    	    			 }
    	    		 
    	    			 wx.chooseImage({
    	        	     	 success: function (res) {
    	        	       		 images.localId = res.localIds;
    	        	        	console.log('已选择 ' + res.localIds.length + ' 张图片');
    	        	        
    	        	        	var i = 0, length = images.localId.length;
    		        	    	images.serverId = [];
    		        	    	
    		        	   		 function upload() {
    		        	     		 wx.uploadImage({
    		        	       			 localId: images.localId[i].toString(),
    		        	        		isShowProgressTips: images.localId[i].toString(),
    		        	       			 success: function (res) {
    		        	        		  i++;
    		        	         		 console.log('已上传：' + i + '/' + length);
    		        	        		//返回图片的服务器端ID res.serverId,然后调用wxImgCallback函数进行下载图片操作
                                		  wxImgCallback(check_id,imagename,res.serverId);
    		        	       		//   images.serverId.push(res.serverId);
    		        	        		  if (i < length) {
    		        	           			 upload();
    		        	          				}
    		        	       				 },
    		        	       			 fail: function (res) {
    		        	        			console.log(res);
    		        	        			}	
    		        	      			});
    		        	   			 }
    		        	   		 
    		        	    		upload();   	        	     	
    	        	     		 }
    	        	   	 	});
    		        	  */
    		       	 }
    		    });
    	  
    	   }); 
    	
    });
    
    url=document.location.toString();

	 $.ajax({
	     url : "../../../wechat/sign.do",
	     data : {
	    	 campusId:1,
	    	 url:url
	     },
	     async: false,
	     type : "GET",
	     success : function(data) {
	    	 var ticket=JSON.parse(data);
	    	 
	    	 wx.config({
	    		debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
	      		appId: ticket.appId,
	      		timestamp: ticket.timestamp,
	      		nonceStr: ticket.nonceStr,
	      		signature: ticket.signature,
	      		jsApiList : [ 'checkJsApi', 'onMenuShareTimeline',
	                            'onMenuShareAppMessage', 'onMenuShareQQ',
	                            'onMenuShareWeibo', 'hideMenuItems',
	                            'showMenuItems', 'hideAllNonBaseMenuItem',
	                            'showAllNonBaseMenuItem', 'translateVoice',
	                            'startRecord', 'stopRecord', 'onRecordEnd',
	                            'playVoice', 'pauseVoice', 'stopVoice',
	                            'uploadVoice', 'downloadVoice', 'chooseImage',
	                            'previewImage', 'uploadImage', 'downloadImage',
	                            'getNetworkType', 'openLocation', 'getLocation',
	                            'hideOptionMenu', 'showOptionMenu', 'closeWindow',
	                            'scanQRCode', 'chooseWXPay',
	                            'openProductSpecificView', 'addCard', 'chooseCard',
	                            'openCard' ]
	      	});
       	    	    	
       	     
	    	 document.querySelector('#showPicker').onclick = function () {
	    		 
	    		 var images = {
	        	   		 localId: [],
	        	    	serverId: []
	        	  	   };
	    		 
	    		 var imagename=prompt("请输入安全巡查图片的名称 : ","");
	    		 
	    		 if(imagename==null){
	    			 imagename="无标题";
	    		 }
	    		 
	    		 wx.chooseImage({
	        	      success: function (res) {
	        	        images.localId = res.localIds;
	        	        console.log('已选择 ' + res.localIds.length + ' 张图片');
	        	        
	        	        var i = 0, length = images.localId.length;
		        	    images.serverId = [];
		        	    function upload() {
		        	      wx.uploadImage({
		        	        localId: images.localId[i].toString(),
		        	        isShowProgressTips: images.localId[i].toString(),
		        	        success: function (res) {
		        	          i++;
		        	          console.log('已上传：' + i + '/' + length);
		        	        //返回图片的服务器端ID res.serverId,然后调用wxImgCallback函数进行下载图片操作
                               wxImgCallback(check_id,imagename,res.serverId);
		        	       //   images.serverId.push(res.serverId);
		        	          if (i < length) {
		        	            upload();
		        	          }
		        	        },
		        	        fail: function (res) {
		        	        	console.log(res);
		        	        }
		        	      });
		        	    }
		        	    upload();
	        	      }
	        	    });
	    		 
	    		 
	    	 }
       	     
	      }
	 });

	 function wxImgCallback(check_id,imagename,serverId) {
		 console.log("serverId="+serverId);
		    //将serverId传给wx_upload.php的upload方法
		    var url = "../../file/upload.do";
		    $.get(url,{
		    	campusId:1,
		    	imagename:imagename,
		    	serverId:serverId,
		    	id:check_id,
		    	classType:"check"
		    }, function(data){
		    	console.log(data);
		        if (data == 0) {
		        	alert("上传图片失败!");
		        	console.log(data.msg);
		        } else if (data == 1) {
		            //存储到服务器成功后的处理
		            //
		            alert("上传图片"+name+"成功!");
		            location.href="CheckInfoDetail.html?check_id="+check_id+"&latitude="+latitude+"&longitude="+longitude;
		        }
		    });
		}		
    
</script>

<script src="../../../js/previewImage.min.js"></script>

<script>
 
 var im = {};
 /**
  * 得到多个元素
  * @public
  */
 im.all = function(selector, contextElement) {
     var nodeList,
         list = [];
     if (contextElement) {
         nodeList = contextElement.querySelectorAll(selector);
     } else {
         nodeList = document.querySelectorAll(selector);
     }
     if (nodeList && nodeList.length > 0) {
         list = Array.prototype.slice.call(nodeList);
     }
     return list;
 }

 /**
  * 将事件委托给父元素
  * @public
  * @param  array     $el         父元素
  * @param  string    eventType  事件类型名称
  * @param  string    selector   目标的选择器
  * @param  function  fn
  */
 im.delegate = function($el, eventType, selector, fn) {
     if (!$el) { return; }
     $el.addEventListener(eventType, function(e) {
         var targets = im.all(selector, $el);
         if (!targets) {
             return;
         }
         // findTarget:
         for (var i=0; i<targets.length; i++) {
             var $node = e.target;
             while ($node) {
                 if ($node == targets[i]) {
                     fn.call($node, e);
                     break; //findTarget;
                 }
                 $node = $node.parentNode;
                 if ($node == $el) {
                     break;
                 }
             }
         }
     }, false);
 };


 im.delegate(document.querySelector('#img'), 'click','img',function(){
	 
	 var urls = [];
	 var imgs = im.all('img',im.all('#img')[0]);
	 imgs.forEach(function(v,i){
		 var str=v.src;
		 var url=str.replace(/\/compressFile/, "");
	     urls.push(url);
	 })
     
	 var thisStr = this.src;
	 var current = thisStr.replace(/\/compressFile/, "");
	 console.log(current);
     var obj = {
         urls : urls,
         current : current
     };
     previewImage.start(obj);
 });
 
</script>
